package org.sixtynine.stock.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sixtynine.stock.Constants.CommonData;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.CategoryModule;
import org.sixtynine.stock.entity.Module;
import org.sixtynine.stock.entity.User;
import org.sixtynine.stock.entity.UserCategory;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.util.SessionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Do back end authentication through this
 * 
 * @author Thilanka
 * 
 */
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

	private static final String ADMIN_URL = "/admin/";
	private static final String MYACCOUNT_URL = "/myaccount";

	private String adminUser;

	@Autowired
	private GenericService genericService;

	@Autowired
	private DataManagerService dataManagerService;

	private static final String ADMIN_USER_CATEGORY = "admin";
	private static final String REQUEST_PARAM_MODULE = "module";

	private List<String> getModules(User user) {
		UserCategory userCategory = (UserCategory) genericService.findById(user
				.getUserCategory().getId(), UserCategory.class);

		List<BaseEntity> modules = dataManagerService.getData(CommonData.MODULE
				.toString());

		List<String> validModules = new ArrayList<String>();
		for (BaseEntity baseEntity : modules) {
			Module module = (Module) baseEntity;
			for (CategoryModule categoryModule : userCategory
					.getCategoryModule()) {
				if (categoryModule.getModule().getId() == module.getId()) {
					validModules.add(module.getName());
				}
			}
		}

		return validModules;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String uri = request.getRequestURI();

		SessionBean sessionBean = SessionBean.getInstance(request);
		User user = sessionBean.getUser();

		// module code send for the security validation
		String moduleCode = request.getParameter(REQUEST_PARAM_MODULE);

		boolean userLogged = false;
		if (user != null) {
			userLogged = true;
			request.setAttribute("userName", user.getUserName());

			if (uri.contains(MYACCOUNT_URL)) {
				if (user.getUserCategory().getName().equals(getAdminUser())) {
					response.sendRedirect("/StockScreener/admin/admin_home");
					return false;
				}
			}

			if (moduleCode != null) {
				List<String> modules = getModules(user);
				if (!modules.contains(moduleCode)) {
					// going to upgrade
					response.sendRedirect("/StockScreener/myaccount/main.html?message=Please upgrade your account");
					return false;
				}
			}

		} else {
			if (uri.contains(ADMIN_URL)) {
				response.sendRedirect("/StockScreener/login/login");
				return false;
			}

			// if user not logged, but going to access special features
			if (moduleCode != null) {
				response.sendRedirect("/StockScreener/login/login?message=Please login to access this features");
				return false;
			}
		}
		request.setAttribute("userLogged", userLogged);

		return true;
	}

	public String getAdminUser() {
		return adminUser;
	}

	public void setAdminUser(String adminUser) {
		this.adminUser = adminUser;
	}

}
